package io.mft.commons.db.mapper;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

import io.mft.commons.db.mapper.annotation.BeanMapper;
import io.mft.commons.db.mapper.exception.MapperException;

public class BeanListMappingParser {
	public static BeanListMapping parse(Method method) {
		BeanListMapping beanListMapping=new BeanListMapping();
		Class<?> returnType=method.getReturnType();
		if (returnType.equals(List.class)) {
			Class<?> mapperType=getBeanListMapperType(method);
			if (mapperType!=null&&!mapperType.equals(Void.class)) {
				BeanMapper beanMapper=mapperType.getAnnotation(BeanMapper.class);
				if (beanMapper!=null) {
					beanListMapping.setMapperType(mapperType);
					beanListMapping.setCanMapping(true);
				}else {
					throw new MapperException("集合bean查询必须添加@BeanMapper注解，请检查["+method.getDeclaringClass().getName()+"."+method.getName()+"]返回的集合元素的类型是否添加@BeanMapper注解");
				}
			}else {
				if (Void.class.equals(mapperType)) {
					throw new MapperException("集合bean查询必须指定映射类型，请检查["+method.getDeclaringClass().getName()+"."+method.getName()+"]的注解@BeanMapper初始化值");
				}
			}
		}
		return beanListMapping;
	}
	private static Class<?> getBeanListMapperType(Method method) {
		Annotation[] annotations=method.getAnnotations();
		Class<?> type=null;
		for (Annotation annotation : annotations) {
			if (annotation instanceof BeanMapper) {
				type=((BeanMapper) annotation).mapperType();
				break;
			}
		}
		return type;
	}
}
